package main

import (
	"context"
	"encoding/base64"
	"flag"
	"fmt"
	v1 "github.com/k3s-io/helm-controller/pkg/apis/helm.cattle.io/v1"
	helmv1 "github.com/k3s-io/helm-controller/pkg/generated/clientset/versioned/typed/helm.cattle.io/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"os"
	"path/filepath"
)

// --kubeconfig=/etc/rancher/k3s/k3s.yaml
func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	// use the current context in kubeconfig
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	// create the clientset
	clientset, err := helmv1.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	cli := helmv1.New(clientset.RESTClient())
	fmt.Printf("%v\n", clientset.RESTClient().APIVersion())
	charts, err := cli.HelmCharts("kube-system").List(
		context.TODO(), metav1.ListOptions{})
	if err != nil {
		panic(err)
	}
	fmt.Printf("charts number %d\n", len(charts.Items))
	fmt.Println("-------------------------------------------------")

	/*dsEndChart := v1.NewHelmChart("default", "ds01", v1.HelmChart{
	Spec: v1.HelmChartSpec{
		Chart: "stable/traefik",
		Set: map[string]intstr.IntOrString{
			"rbac.enabled":                 intstr.Parse("true"),
			"ssl.enabled":                  intstr.Parse("false"),
			"acme.dnsProvider.name":        intstr.Parse("cloudflare"),
			"global.clusterCIDR":           intstr.Parse("10.42.0.0/16,fd42::/48"),
			"global.systemDefaultRegistry": intstr.Parse(""),
		},
	}})*/

	namespace := "default"
	//release := "ds02"
	release := "ds-mq-redis-edge"
	chartZip := "/home/lynn/go/src/git.inspur.com/zdp/data-sync/chart/data-sync-0.1.tgz"
	chart, err := CreateHelmChart(cli, chartZip, namespace, release)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%v\n", chart)

	/*err = DeleteHelmChart(cli, namespace, release)
	if err != nil {
		panic(err)
	}

	release2 := "ds-redis-td-edge"
	err = DeleteHelmChart(cli, namespace, release2)
	if err != nil {
		panic(err)
	}*/

}

func CreateHelmChart(client *helmv1.HelmV1Client, chartZip, namespace, release string) (*v1.HelmChart, error) {
	bytes, err := os.ReadFile(chartZip)
	if err != nil {
		panic(err)
	}

	base64 := base64.StdEncoding.EncodeToString(bytes)
	dsEndChart := v1.NewHelmChart(namespace, release, v1.HelmChart{
		Spec: v1.HelmChartSpec{
			//Chart:        "data-sync",
			//Version:      "0.1",
			//Repo:         "",
			HelmVersion:  "v3",
			ChartContent: base64,
			//ValuesContent: "{\"hostname\": \"ubuntu-20-lts\", \"image\":\"yuanxl/datasync:v0.1\"}", // ubuntu-20-lts
			ValuesContent: "{\"image\":\"yuanxl/datasync:v0.1\",\"hostname\":\"ubuntu-20-lts\",\"properties\":{\"id\":\"0001\",\"name\":\"end01\",\"description\":\"data from kafka to redis timeseries\"},\"resources\":{\"requests\":{\"memory\":\"128Mi\",\"cpu\":\"100m\"},\"limits\":{\"memory\":\"256Mi\",\"cpu\":\"500m\"}},\"config\":{}}",
			//Set: map[string]intstr.IntOrString{
			//	"rbac.enabled":                 intstr.Parse("true"),
			//	"ssl.enabled":                  intstr.Parse("false"),
			//	"acme.dnsProvider.name":        intstr.Parse("cloudflare"),
			//	"global.clusterCIDR":           intstr.Parse("10.42.0.0/16,fd42::/48"),
			//	"global.systemDefaultRegistry": intstr.Parse(""),
			//},
		}})
	return client.HelmCharts(namespace).Create(
		context.TODO(),
		dsEndChart,
		metav1.CreateOptions{
			//DryRun: []string{"All"},
		})
}

func DeleteHelmChart(client *helmv1.HelmV1Client, namespace, release string) error {
	err := client.HelmCharts(namespace).Delete(context.TODO(), release, metav1.DeleteOptions{})
	if err != nil {
		return err
	}

	return nil
}
